﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Data.SqlClient;

namespace Forget.HRBLL
{
    public class Convert<T> where T : class
    {
        /// <summary>
        /// 将表中的行转换为指定类型的对象
        /// </summary>
        /// <param name="row">数据表中的行</param>
        /// <returns>指定类型的对象</returns>
        public static T DataConvertToObject(DataRow row)
        {
            Type t = typeof(T);
            T obj = (T)t.Assembly.CreateInstance(t.FullName);
            bool isTrue = false;
            foreach (DataColumn column in row.Table.Columns)
            {
                PropertyInfo property = t.GetProperty(column.ColumnName);
                if (property != null && row[column.ColumnName]!=DBNull.Value)
                {
                    property.SetValue(obj, row[column.ColumnName], null);
                    isTrue = true;
                }
            }
            obj = isTrue ? obj : null;
            return obj;
        }

        /// <summary>
        /// 将表转换为指定类型的集合
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static List<T> DataConvertToObject(DataTable table)
        {
            List<T> users = new List<T>();
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    T tmp = Convert<T>.DataConvertToObject(row);
                    if (tmp != null) users.Add(tmp);
                }
            }
            return users;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<SqlParameter> ObjectToParms(object obj)
        {
            List<SqlParameter> parms = new List<SqlParameter>();
            PropertyInfo[] pis = obj.GetType().GetProperties();
            foreach (var p in pis)
            {
                object[] dpas = p.GetCustomAttributes(typeof(DataParamAttribute), true);
                object proValue = p.GetValue(obj, null);
                if (proValue is DateTime && ((DateTime)proValue) == DateTime.MinValue)
                    continue;
                if (proValue!=null && dpas != null && dpas.Length > 0)
                {
                    DataParamAttribute dpa = (DataParamAttribute)dpas[0];
                    SqlParameter parm = new SqlParameter();
                    parm.ParameterName = string.Format("@{0}", p.Name.ToLower());
                    parm.SqlDbType = dpa.SqlDbType;
                    if (dpa.Size > 0)
                        parm.Size = dpa.Size;
                    parm.Value = proValue;
                    parms.Add(parm);
                }
            }
            return parms;
        }
    }
}
